// pages/cats/cats.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    array1:[31,28,31,30,31,30,31,31,30,31,30,31],
    // 触摸开始时间
    touchStartTime: 0,
    // 触摸结束时间
    touchEndTime: 0,
    // 最后一次单击事件点击发生时间
    lastTapTime: 0,
    // 单击事件点击后要触发的函数
    lastTapTimeoutFunc: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options',options)
    if(options.animals_id){
      this.getanimalsdetail(options.animals_id)
    }
  },
  getanimalsdetail(_id){
    var that = this
    this.myShowToast('加载中');
    wx.cloud.callFunction({
      name: 'getanimalsdetail',
      data:{
        _id:_id
      }
    }).then(res=>{
        var album = res.result.album.data
        var album_len = 0
        for(var i=0;i<album.length;i++){
            var obj = album[i]
            album_len += obj.animals_photo.length
        }
        that.setData({
          animals:res.result.animals.data[0],
          album:res.result.album.data,
          album_len:album_len
        }),wx.hideToast();
    })
  },



  goanimals(e){
    console.log('e',e)
    const animals_id = e.currentTarget.dataset._id
    wx.navigateTo({
      url: './cats?animals_id=' +animals_id,
    })
  },
  onShareAppMessage: function() {
    return {
        title: this.data.animals.name,
        path: "/pages/cats/cats?animals_id=" + this.data.animals._id,
        success: function(t) {},
        fail: function(t) {}
    };
},
  // 转发到朋友圈
  onShareTimeline: function (res) {
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      console.log(ops.target)
    }
    return {
      path: 'pages/cats/cats?animals_id=' + this.data.animals._id,  // 路径，传递参数到指定页面。
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  },
  web_stroy(){
      if(this.data.animals.story_url){
        wx.navigateTo({
            url: '../web_view/web_view?_id='+ this.data.animals._id,
          })
      }
  },
myShowToast(title = '标题') {
  wx.showToast({
    title: title,
    image:'/pages/images/loading.gif',
    size: 700,
    mask: true
  })
},
showPopularityTip() {
  wx.showToast({
    title: '动物人气值',
    icon: "none"
  });
},
bindImageLoaded(){
  let Arraylist = []
  Arraylist.push(this.data.animals.picture)
  wx.previewImage({
      current: [0], // 当前显示图片的http链接
      urls: Arraylist // 需要预览的图片http链接列表
  })
},
handleTouchStart: function(e) {    
  this.startTime = e.timeStamp;    
  //console.log(" startTime = " + e.timeStamp);  
},
//touch end
handleTouchEnd: function(e) {    
  this.endTime = e.timeStamp;    
  //console.log(" endTime = " + e.timeStamp);  
},  

showAnimalPic(){
  if (this.endTime - this.startTime < 350) {  
  wx.previewImage({
    current: [0], // 当前显示图片的http链接
    urls: this.data.animals.photos // 需要预览的图片http链接列表
})
  }
},
handleLongPress: function(e) {
  var that = this
  //console.log("endTime - startTime = " + (this.endTime - this.startTime));
  try {
    if(this.data.animals.video.length>0){
      let animals_video = that.data.animals.video
      let video = []
      animals_video.forEach(element => {
        let obj = {}
        obj.url = element,
        obj.type = 'video'
        video.push(obj)
      }),wx.previewMedia({
        sources:video
      })  
    }else{
      wx.showToast({
        title: '还没有小动物视频！',
        icon: "none"
      });
    }
  }catch{
    wx.showToast({
      title: '还没有小动物视频！',
      icon: "none"
    });
  }
  },
    // 单击、双击
    multipleTap(e) {
      var that = this
      let _id = e.currentTarget.dataset._id
      let popularity = e.currentTarget.dataset.popularity
      // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
      if (that.touchEndTime - that.touchStartTime < 350) {
        // 当前点击的时间
        var currentTime = e.timeStamp;
        var lastTapTime = that.lastTapTime;
        // 更新最后一次点击时间
        that.lastTapTime = currentTime;
        // 如果两次点击时间在300毫秒内，则认为是双击事件
        if (currentTime - lastTapTime < 300) {
          console.log("double tap");
          // 成功触发双击事件时，取消单击事件的执行
          clearTimeout(that.lastTapTimeoutFunc);
          if(this.time(wx.getStorageSync(this.data.animals.name)?wx.getStorageSync(this.data.animals.name):'')){
          wx.cloud.callFunction({
            name: 'upanimalshot',
            data:{
              _id:_id,
              popularity:popularity
            }
          }).then(res=>{
            console.log('res',res)
            if(res.result.errMsg == 'document.update:ok'){
              if(res.result.stats.updated == 1){
                wx.showToast({
                  title: '打call成功',
                  icon: "none"
                }),wx.setStorageSync(this.data.animals.name,Date.parse(new Date())),this.onLoad({animals_id:_id});
                return;
              }
              if(res.result.stats.updated == 0){
                wx.showToast({
                  title: '打call失败',
                  icon: "none"
                });
                return;
              }
            }
          })
        }else{
          wx.showToast({
            title: '您今天已经为它打过call了，请明天再来',
            icon: "none"
          })
        }
        } else {
          // 单击事件延时300毫秒执行，这和最初的浏览器的点击300ms延时有点像。
          that.lastTapTimeoutFunc = setTimeout(function () {
            console.log("tap");
            wx.showToast({
              title: '动物人气值(双击为它打call)',
              icon: "none"
            });
          }, 300);
        };
      }
    },
     // 按钮触摸开始触发的事件
    touchStart: function (e) {
      this.touchStartTime = e.timeStamp;
    },
      // 按钮触摸结束触发的事件
    touchEnd(e) {
      this.touchEndTime = e.timeStamp;
    }, // 按钮触摸结束触发的事件

    //时间判断
    time:function(animalstime){ 
      console.log('state1',animalstime)                      //res是你从数据库拿到的数据
      var datenow = new Date();                    //获取当前时间戳
      var month1 = datenow.getMonth() + 1;
      var date11 = datenow.getDate();
      var year1=datenow.getDate;
         //res.data是你拿从数据库拿到的数据数组
      var jude = Math.floor((datenow-animalstime)/1000)
      console.log(jude)
        var date1 = new Date(animalstime);       //time是你数据的时间戳
        var year = date1.getFullYear();
        var month = date1.getMonth() + 1;
        var date = date1.getDate();
        if(year1%4===0){                               //闰年2月多一天
          this.data.array[1]=29
        }
      console.log(month1, date11, month, date)
        
        var result=this.reduce(month1,date11,month,date)
        console.log(result)
        if(animalstime == ''){
          return true;
        }
         if (result.result===0) {  
           console.log('是今天')
          return false;
        }
        if (result.result===1){
          return true;
        }
      },
      reduce:function(res1,res2,res3,res4){       //得出相差天数并返回
        var sum1=0,sum2=0;
          if(res1===1){
            sum1=this.data.array[1]===28?365:366
          }
          for(var i=0;i<res1-1;i++){
             sum1=sum1+this.data.array1[i];
          }
          for(var i=0;i<res3-1;i++){
            sum2=sum2+this.data.array1[i]
          }
          console.log(sum1,sum2)
        var result = sum1+res2-sum2-res4
          return{
             result
          }
      },
      bindTapPhoto(e){
          console.log(e)
          let index = e.currentTarget.dataset.index
          let idx = e.currentTarget.dataset.idx
          let Arraylist = this.data.album[idx].animals_photo
          console.log(index)
          wx.previewImage({
              current: Arraylist[index], // 当前显示图片的http链接
              urls: Arraylist // 需要预览的图片http链接列表
          })
      }
})